/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.market.web;

import com.market.web.ChatConnection;
import java.io.IOException;
import java.util.Date;
import javax.annotation.security.DeclareRoles;
import javax.annotation.security.RolesAllowed;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.glassfish.sse.api.ServerSentEventContext;
import org.glassfish.sse.api.ServerSentEventData;
import org.glassfish.sse.api.ServerSentEventHandlerContext;

/**
 *
 * @author project
 */


@WebServlet("/chat")
public class ChatServlet extends HttpServlet {
    
    @Inject @ServerSentEventContext("/chatroom")
    ServerSentEventHandlerContext<ChatConnection> connections;

    @Override
    protected void doPost(HttpServletRequest req
            , HttpServletResponse resp) throws ServletException, IOException {
        String message = req.getParameter("message");
        String roomName = req.getParameter("roomName");
        
        System.out.println("----> the message: " + message);
        System.out.println("---> roomName: " + roomName);
        
        ServerSentEventData data = new ServerSentEventData();
        JsonObjectBuilder b = Json.createObjectBuilder();
        b.add("text", message)
                .add("time", new Date().toString());
        data.data(b.build().toString());
        data.event(roomName);
        for (ChatConnection c: connections.getHandlers())
            c.send(data);                
        
        resp.setContentType("text/plain");
        resp.setStatus(HttpServletResponse.SC_OK);
    }
}
    
